package com.study.demo.data;

import com.stduy.util.Logger;
import com.study.demo.data.local.ForumLocalDataSource;
import com.study.demo.data.remote.ForumRemoteDataSource;
import com.study.demo.db.Forum;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;

/**
 * Created by sll on 2016/6/3.
 */
public class ForumRepository implements ForumDataSource {


    private final ForumLocalDataSource mForumLocalDataSource;
    private final ForumRemoteDataSource mForumRemoteDataSource;

    @Inject
    public ForumRepository(ForumLocalDataSource mForumLocalDataSource,
                           ForumRemoteDataSource mForumRemoteDataSource) {
        this.mForumLocalDataSource = mForumLocalDataSource;
        this.mForumRemoteDataSource = mForumRemoteDataSource;
    }

    @Override
    public Observable<List<Forum>> getForumList(String forumId) {
        Logger.d("getForumList:" + forumId);
        Observable<List<Forum>> remote = mForumRemoteDataSource.getForumList(forumId);
        Observable<List<Forum>> local = mForumLocalDataSource.getForumList(forumId);

        Observable<List<Forum>> remoteWithLocalUpdate = remote.doOnNext(
                forumList -> {
                    if (forumList != null) {
                        forumList.forEach(forum -> mForumLocalDataSource.saveForum(forum));
                    }
                });
        if (forumId.equals("0")) {  //我的论坛强制刷新
            return remoteWithLocalUpdate;
        }

        return Observable.concat(local, remoteWithLocalUpdate)
                .takeUntil(forumList -> forumList != null && !forumList.isEmpty()
                );
    }

    @Override
    public Observable<Boolean> removeForum(String fid) {
        return null;
    }
}
